import { BufferAsset, resources } from "cc"
import { ResourceManager } from "./ResourceManager"
import Singleton from "../Base/Singleton"
// import sproto from "../sproto-js-master/sproto.js"
import sproto from "../sproto-js-master/sproto.js"


const c2ssproto = `sproto_spd/c2s`;
const s2csproto = `sproto_spd/s2c`;
export class SprotoManager extends Singleton  {
	static get Instance() {
		return super.GetInstance<SprotoManager>()
	}
    client_host=undefined
    client_request=undefined
    buffer=new Uint8Array(1024)
    bufferoffset:number=0
    async init(){
		// resources.preloadDir("sproto",BufferAsset)
		const c2s= await this.readBinary(c2ssproto)
		const s2c= await this.readBinary(s2csproto)
		
		// console.log(sproto)
    const clientsproto = sproto.createNew(c2s);
    const serversproto= sproto.createNew(s2c);
    this.client_host=serversproto.host()
    this.client_request=this.client_host.attach(clientsproto)
	console.log("sproto初始化充公")
}
    async readBinary(filename:string):Promise<ArrayBuffer>{
        const buffer=await ResourceManager.Instance.loadBinary(filename)
        if(!buffer){
            console.log("cont find")
        }
        return buffer
    }
	pack(tag:string,args=null,session:number=null){
		const array=this.client_request(tag,args,session)
		return new Uint8Array(array)
	}
    recv_package(data:ArrayBuffer)
{
	const tdate=new Uint8Array(data)
	// this.buffer.set(tdate,this.bufferoffset)
	// // tdate.copy(this.buffer,this.bufferoffset)
	// // data.copyWithin(buffer,bufferoffset)
	// this.bufferoffset+=tdate.length
	
	// if(this.bufferoffset<2){
	// 	return
	// 	//todo存入缓存
	// }else{
	// 	//todo获得长度
	// 	const s=this.buffer[0]*256+this.buffer[1]
	// 	if(this.bufferoffset<s+2){
	// 		//todo,继续缓存
	// 		return
	// 	}else{
	// 		// console.log(buffer.toString("hex"))
	// 		const b1=this.buffer.subarray(2,2+s)

	// 		// this.buffer.copy(this.buffer,0,s+2,this.bufferoffset)
	// 		const minibuffer=this.buffer.subarray(2+s,this.bufferoffset)
	// 		this.buffer.set(minibuffer)
	// 		this.bufferoffset-=(2+s)

			const ret=this.client_host.dispatch(tdate)
			return ret
			
			//todo解析数据
		}
	}
// }}






// export class sprotoDispath{
